const userService = require("../service/user.service");
const errorType = require("../constants/error-types");
const md5Password = require("../utils/password-handle");
const app = require("../app");
//注册 验证用户信息
const verifyUser = async (ctx, next) => {
  const { name, password, email } = ctx.request.body;
  console.log(ctx.request.body);
  // 必填项
  try {
    if (!name || !password || !email) {
      console.log(name, password, email);
      const error = new Error(errorType.NAME_OR_PASSWORD_AND_EMAIL_IS_REQUIRED);
      return ctx.app.emit("error", error, ctx);
    }
    // 名字是否重复
    const resultName = await userService.getUserByName(name);
    console.log(resultName, "getUserByName");
    if (resultName) {
      const error = new Error(errorType.USER_ALREADY_EXISTS);
      return ctx.app.emit("error", error, ctx);
    }
    console.log("用户注册检测是否重名");
    // 邮箱是否重复
    const resultEmail = await userService.getEmail(email);
    console.log(email, "getEmail");
    if (resultEmail) {
      const error = new Error(errorType.EMAIL_IS_EXISTS);
      return ctx.app.emit("error", error, ctx);
    }
    console.log("用户注册检测Email是否已注册");
    await next();
  } catch (error) {
    console.log(error);
  }
};
// 密码md5加密;
const handledPassword = async (ctx, next) => {
  console.log("密码md5加密");
  let { password } = ctx.request.body;
  ctx.request.body.password = md5Password(password);
  await next();
};

module.exports = {
  verifyUser,
  handledPassword,
};
